package com.liuwa.common.utils.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description:
 * @Author: Liuwa
 * @Date: 2023/11/12 20:52
 */
public class ZipUtils {

    public static void zipFiles(List<File> files, File zipFile) {
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zipOut = new ZipOutputStream(fos)) {

            for (File file : files) {
                addToZip(file, zipOut);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加入压缩包
     * @param file
     * @param zipOut
     * @throws IOException
     */
    private static void addToZip(File file, ZipOutputStream zipOut) throws IOException {
        if(!file.exists()) {
            return;
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zipOut.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }

            zipOut.closeEntry();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}